package com.lanou.musicbox.activity;


import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RemoteViews;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.toolbox.ImageLoader;
import com.lanou.musicbox.R;
import com.lanou.musicbox.adapter.localmusic.PopupWindowAdapter;
import com.lanou.musicbox.base.BaseActivity;
import com.lanou.musicbox.base.BaseApplication;
import com.lanou.musicbox.bean.Recommend;
import com.lanou.musicbox.custom.Events;
import com.lanou.musicbox.entity.Entity;
import com.lanou.musicbox.fragment.IMusicBackService;
import com.lanou.musicbox.fragment.MainFragmentAll;
import com.lanou.musicbox.fragment.localmusic.CollectFragment;
import com.lanou.musicbox.fragment.localmusic.LocalityFragment;
import com.lanou.musicbox.fragment.onlinemusic.EnterThePlaylistFragment;
import com.lanou.musicbox.service.MusicService;
import com.lanou.musicbox.utils.MyConfig;
import com.lanou.musicbox.utils.VolleySingleton;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by 杨海宁 on 15/10/24.
 * main 及音乐窗口的控制,返回按键的设置
 */
public class MainActivity extends BaseActivity
        implements View.OnClickListener,
        CollectFragment.CollectMusic, LocalityFragment.PassLocalMusic, AdapterView.OnItemClickListener {

    // 以下是抽屉的定义内容
    private LinearLayout scan;
    private LinearLayout linear_main;
    private LinearLayout changeSkinID;
    private LinearLayout sleepID;
    private TextView exit_app;
    private DrawerLayout drawerLayout;
    private FragmentManager manager;
    private FragmentTransaction transaction;

    public static final int MSG_UPDATE_UI = 0;
    public static final int MSG_UPDATE_SEEKBAR = 1;
    public static final int MSG_UPPALY_BTN = 2;
    public static final String UPDATE_UI = "com.aidl.music.updateui";
    private ImageView bottom_img;//图片
    private TextView bottom_title;//歌曲名字
    private TextView bottom_singer;//演唱者
    private TextView songs_count_time;
    private TextView songs_current_time;
    private Button bottom_next;//下一曲
    private Button bottom_pause;//开始
    private Button bottom_up;  //上一曲
    private IMusicBackService mService; // 定义音乐进程
    private List<Entity> mList;
    private boolean isHaveMusic = false;
    private String duration;
    private String current_time;
    private String Artist, songs_name;
    private String img_url, big_img;
    private ImageLoader imageLoader;

    private View view;
    private PopupWindow popupWindow;
    public static Context mContext;
    //登陆属性
    private String screen_name, profile_image_url;
    private CircleImageView landing_image;
    private TextView landing_name;
    private ListView listView;
    private String whatMusic;

    private LinearLayout bottm_music_info;


    private RemoteViews remoteViews;
    private UpdateUiBroadcastReceiver mUpdateUiBroadcastReceiver; //定义全局监听器
    // 为后台播放通知创建对象

    private String TAG = "lanou99999";

    /**
     * 第三方登陆
     **/
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_drawer);
        mList = new ArrayList<>();
        MainFragmentAll fragment = new MainFragmentAll();
        manager = getSupportFragmentManager();
        transaction = manager.beginTransaction();
        transaction.replace(R.id.fill_main, fragment);
        transaction.commit();
        // 启动service
        startService(new Intent(this, MusicService.class));
        //注册 EventBus
        EventBus.getDefault().register(this);
        //图片请求初始化
        imageLoader = VolleySingleton.getInstance(this).getImageLoader();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(UPDATE_UI); // 添加动作
        // registerReceiver注册方法 (动态注册)
        mUpdateUiBroadcastReceiver = new UpdateUiBroadcastReceiver();
        this.registerReceiver(mUpdateUiBroadcastReceiver, intentFilter);
        /**
         * 构造方法初始化
         * ***/
        imageLoader = VolleySingleton.getInstance(this).getImageLoader();

        initdata();
        if (mList != null && mList.size() > 0) {
            isHaveMusic = true;
            Log.i(TAG, "onEvent_is ");
        }
        musicPopupWindow();
    }

    /**
     * 创建构造方法传数据
     **/
    public void setFragment(int position, ArrayList<Recommend.PicEntity> data) {
        EnterThePlaylistFragment fragment = new EnterThePlaylistFragment();
        Bundle bundle = new Bundle();
        bundle.putString("songs_id", data.get(position).getCode());
        fragment.setArguments(bundle);
        getSupportFragmentManager()
                .beginTransaction()
                .addToBackStack(null)
                .replace(R.id.fill_main, fragment)
                .commit();

    }
    public void onEvent(Events.NewSongsEvent musicInfoEvent) {
        mList = musicInfoEvent.getSongsInfos();
        whatMusic = musicInfoEvent.getWhatMusic();
        if (mList != null && mList.size() > 0) {
            isHaveMusic = true;
        }

    }

    /**
     * 本地音乐
     * 获取IMusicBackService对象，当调用bindService会执行onServiceConnected，
     */
    private ServiceConnection mRemoteConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mService = IMusicBackService.Stub.asInterface(service);
            // 启动线程
            new Thread(new MyThread()).start();
            //开启刷新开始键的线程
            new Thread(new UpPlayBtnThread()).start();
        }

        //服务连接不成功
        @Override
        public void onServiceDisconnected(ComponentName name) {
            mService = null;
        }
    };

    @Override
    public void onStart() {
        bindService(new Intent(this, MusicService.class), mRemoteConnection, Context.BIND_AUTO_CREATE);
        super.onStart();
    }

    //停止
    @Override
    public void onStop() {
        super.onStop();
    }

    //销毁
    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mUpdateUiBroadcastReceiver);
        try {

            unbindService(mRemoteConnection);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /***
     * 构造方法
     * 初始化id
     **/
    private void initdata() {
        // 监听抽屉的整体布局防止点击事件冲突
        linear_main = (LinearLayout) findViewById(R.id.linear_main);
        // 抽屉的监听用来打开或关闭抽屉
        drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
        scan = (LinearLayout) findViewById(R.id.scan);
        changeSkinID = (LinearLayout) findViewById(R.id.changeSkinID);
        sleepID = (LinearLayout) findViewById(R.id.sleepID);
        exit_app = (TextView) findViewById(R.id.ExitID);
        landing_image = (CircleImageView) findViewById(R.id.landing_image);
        landing_name = (TextView) findViewById(R.id.landing_name);
        landing_name.setText("未登录");
        bottom_img = (ImageView) findViewById(R.id.bottom_img);
        bottom_title = (TextView) findViewById(R.id.bottom_title);
        bottom_singer = (TextView) findViewById(R.id.bottom_singer);
        bottom_next = (Button) findViewById(R.id.bottom_next);
        bottom_pause = (Button) findViewById(R.id.bottom_pause);
        bottom_up = (Button) findViewById(R.id.bottom_up);
        songs_current_time = (TextView) findViewById(R.id.songs_current_time);
        songs_count_time = (TextView) findViewById(R.id.songs_count_time);
        bottm_music_info = (LinearLayout) findViewById(R.id.bottm_music_info);

        bottom_img.setOnClickListener(this);
        bottom_next.setOnClickListener(this);
        bottom_pause.setOnClickListener(this);
        bottom_up.setOnClickListener(this);
        //抽屉的按键监听
        drawerLayout.setOnClickListener(this);
        linear_main.setOnClickListener(this);
        scan.setOnClickListener(this);
        changeSkinID.setOnClickListener(this);
        sleepID.setOnClickListener(this);
        exit_app.setOnClickListener(this);
        landing_image.setOnClickListener(this);
        landing_name.setOnClickListener(this);
        bottm_music_info.setOnClickListener(this);
    }

    /**
     * 设置按键的点击事件
     *
     * @param view
     */

    @Override
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.bottom_pause: //开始 暂停

                try {
                    if (isHaveMusic) {
                        if (mService.getMusicIsPlaying()) {
                            bottom_pause.setBackgroundResource(R.drawable.bt_pause_music);
                            mService.pauseMusic();
                        } else {
                            bottom_pause.setBackgroundResource(R.drawable.bt_play_music);
                            mService.playMusic();
                        }
                    }

                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.bottom_next: //下一曲

                try {
                    if (isHaveMusic) {
                        bottom_pause.setBackgroundResource(R.drawable.bt_play_music);
                    }

                    mService.PlayNextMusic();

                    Log.i(TAG, "onClick_bottom_next " + bottom_next);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.bottom_up: //列表
                if (mList != null && mList.size() > 0) {
                    musicPopupWindow();
                    if (popupWindow.isShowing()) {
                        popupWindow.dismiss();
                    } else {

                        popupWindow.showAtLocation(view, Gravity.RIGHT | Gravity.BOTTOM, 0, 140);
                    }
                } else {
                    Toast.makeText(MainActivity.this, "列表加载中,请稍等...", Toast.LENGTH_SHORT).show();
                }


                break;
            //抽屉的点击事件
            case R.id.scan:
                manager = getSupportFragmentManager();
                transaction = manager.beginTransaction();
                transaction.replace(R.id.fill_main, new CollectFragment()).addToBackStack(null).commit();
                break;
            case R.id.changeSkinID:
                Intent intent = new Intent(this, SkinActivity.class);
                startActivity(intent);
                break;
            case R.id.sleepID:
                showSleepDialog();
                break;
            case R.id.ExitID://点击退出应用和音乐服务

                stopService(new Intent(MainActivity.this, MusicService.class));
                android.os.Process.killProcess(android.os.Process.myPid());
                System.exit(0);

                break;
            case R.id.landing_name:
                if (landing_name.getText().equals("未登录")) {
                    Intent intentland = new Intent(this, LandingActivity.class);
                    startActivity(intentland);
                    Log.i("lanou3g", intentland + " ");
                } else if (!(landing_name.getText().equals("未登录")) && landing_name.getText().equals(screen_name)) {
                    Intent intent_name = new Intent(this, LogoutActivity.class);

                    startActivity(intent_name);
                    Log.i("lanou", screen_name + "---------screen_name");

                }
                break;
            case R.id.landing_image:
                break;
            case R.id.bottm_music_info:

                if (whatMusic != null && !whatMusic.equals("本地")) {

                    try {
                        big_img = mList.get(mService.getNowPlay()).getBig_pic();
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                } else {
                    big_img = null;
                }
                Log.i("Sysout", "方法执行了");
                if (mList != null && mList.size() > 0) {
                    PlayActivity.startPlayActivity(this, mList, whatMusic, songs_name, Artist, big_img);
                } else {
                    Toast.makeText(MainActivity.this, "请先选择您喜欢的歌曲", Toast.LENGTH_SHORT).show();
                }

                break;

        }
        // 关闭抽屉
        drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
        // 打开抽屉
        drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
    }

    //设置弹出对话框
    public void showSleepDialog() {

        if (BaseApplication.IS_SLEEP_CLOCK) {
            try {
                mService.cancleSleepClock();
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            Toast.makeText(getApplicationContext(), "已取睡眠模式！",
                    Toast.LENGTH_SHORT).show();
            return;
        }
        View view = View.inflate(this, R.layout.sleep_main, null);
        final Dialog dialog = new Dialog(this, R.style.lrc_dialog);
        dialog.setContentView(view);
        dialog.setCanceledOnTouchOutside(false);

        Window dialogWindow = dialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.CENTER);
        // lp.x = 100; // 新位置X坐标
        // lp.y = 100; // 新位置Y坐标
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int mScreenWidth = metrics.widthPixels;
        lp.width = (int) (mScreenWidth * 0.7); // 宽度
        // lp.height = 400; // 高度

        // 当Window的Attributes改变时系统会调用此函数,可以直接调用以应用上面对窗口参数的更改,也可以用setAttributes
        // dialog.onWindowAttributesChanged(lp);
        dialogWindow.setAttributes(lp);
        dialog.show();
        final TextView cancleBtn = (TextView) view.findViewById(R.id.cancleBtn);
        final TextView okBtn = (TextView) view.findViewById(R.id.okBtn);
        final EditText timeEt = (EditText) view.findViewById(R.id.timeBtn);
        View.OnClickListener listener = new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (v == cancleBtn) {
                    dialog.dismiss();
                } else if (v == okBtn) {
                    String timeS = timeEt.getText().toString();
                    if (TextUtils.isEmpty(timeS)
                            || Integer.parseInt(timeS) == 0) {
                        Toast.makeText(getApplicationContext(), "输入无效！",
                                Toast.LENGTH_SHORT).show();
                        return;
                    }
                    try {
                        mService.setSleepClock(timeS);//设置睡眠时间
                        Toast.makeText(getApplicationContext(), "将在" + timeS + "分钟后退出软件", Toast.LENGTH_SHORT)
                                .show();
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                    dialog.dismiss();
                }
            }
        };

        cancleBtn.setOnClickListener(listener);
        okBtn.setOnClickListener(listener);
    }

    @Override
    protected void onResume() {
        super.onResume();
        profile_image_url = MyConfig.getSharePreStr(this, "profile_image_url", "profile_image_url");
        screen_name = MyConfig.getSharePreStr(this, "screen_name", "screen_name");
        ImageLoader.ImageListener imageListener = ImageLoader.getImageListener(landing_image,
                R.mipmap.reigst_head, R.mipmap.reigst_head);
        imageLoader.get(profile_image_url, imageListener);
        landing_name.setText(screen_name);
        Log.e("XXXXXX", "-------------jinrule   onresume");


    }


    private void musicPopupWindow() {

        view = this.getLayoutInflater().inflate(R.layout.popup_window, null);
        TextView songs_num = (TextView) view.findViewById(R.id.songs_count);
        listView = (ListView) view.findViewById(R.id.popup_listView);
        listView.setCacheColorHint(1);

        if (mList != null && mList.size() > 0) {
            PopupWindowAdapter adapter = new PopupWindowAdapter(this, mList);

            listView.setAdapter(adapter);
            songs_num.setText(mList.size() + "");
        }

        // 创建PopupWindow实例,LayoutParams.FILL_PARENT,LayoutParams.MATCH_PARENT分别是宽度和高度
        popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.FILL_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        //设置外部监听
        popupWindow.setOutsideTouchable(false);//设置非 popupWindow 不可触摸
        popupWindow.setFocusable(true); //可获得焦点
        popupWindow.setTouchable(true); //设置可触摸
        //backgroundAlpha(0.5f);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();

            }
        });
        listView.setOnItemClickListener(this);

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        try {
            Log.i(TAG, "onItemClick  " + position + whatMusic);
            if (mService.getMusicIsPlaying()) {
                mService.stopMusic();
            }
            if (whatMusic != null && whatMusic.equals("网络")) {
                Log.i(TAG, "onItemClick_网络 " + position);
                mService.setNowPlay(position);
            } else {
                mService.setNowPlay(position);
                mService.setDataSourceAndPlay();
            }

        } catch (RemoteException e) {
            e.printStackTrace();
        }

    }


    private boolean mBlRun = true;

    /**
     * 实现接口的回调方法
     **/
    @Override
    public void itemMusicId(int position) {
        try {
            if (mService.getMusicIsPlaying()) {
                mService.stopMusic();

            }
            mService.setNowPlay(position);
            mService.setDataSourceAndPlay();

        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**
     * 用于更新时间和seekbar的线程
     *
     * @author yhn
     */
    public class MyThread implements Runnable {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            while (mBlRun) {
                try {
                    if (mService.getMusicIsPlaying()) {
                        mHandler.sendEmptyMessage(MSG_UPDATE_SEEKBAR);
                    }
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (RemoteException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

    }

    //更新开始暂停按键的线程
    public class UpPlayBtnThread implements Runnable {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            while (mBlRun) {

                mHandler.sendEmptyMessage(MSG_UPPALY_BTN);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }

    }

    /**
     * 当前播放歌曲改变时。activity界面更新
     *
     * @throws RemoteException
     */
    private void updateUi() throws RemoteException {

        if (mList != null && mService.getNowPlay() < mList.size()) {
            Artist = mList.get(mService.getNowPlay()).getArtist();
            songs_name = mList.get(mService.getNowPlay()).getTitle();
            img_url = mList.get(mService.getNowPlay()).getSmall_pic();
            // img_url = mList.get(mService.getNowPlay()).getAlbum();

            bottom_title.setText(songs_name);//歌名
            bottom_singer.setText(Artist);  //歌手
            if (img_url != null && img_url.startsWith("http")) {
                ImageLoader.ImageListener imageListener = ImageLoader.getImageListener(bottom_img, R.mipmap.music_icon_green, R.mipmap.music_icon_green);
                imageLoader.get(img_url, imageListener);
            } else {
                img_url = mList.get(mService.getNowPlay()).getAlbum();
                Log.i(TAG, "updateUi_bitmap0 " + img_url);
                Bitmap bitmap = BitmapFactory.decodeFile(img_url);
                Log.i(TAG, "updateUi_bitmap1 " + bitmap);
                if (bitmap != null) {
                    Log.i(TAG, "updateUi_bitmap2 " + bitmap);
                    remoteViews.setImageViewBitmap(R.id.bottom_img, bitmap);
                } else {
                    bottom_img.setImageResource(R.mipmap.music_icon_green);
                }
            }
        }

    }
    // 根据接收的消息,处理UI更新

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_UPDATE_UI:
                    try {
                        if (mList != null && mList.size() > 0) {
                            updateUi();
                        }
                    } catch (RemoteException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    break;
                case MSG_UPDATE_SEEKBAR:
                    try {
                        current_time = mService.getNowPlayingMusicCurTime();
                        songs_current_time.setText(current_time + "/");//当前的时间
                        duration = mService.getNowPlayingMusicMaxTime();
                        songs_count_time.setText(duration);  //总长度
                        if (mService.getMusicIsPlaying()) {
                            bottom_pause.setBackgroundResource(R.drawable.bt_play_music);
                            Log.i(TAG, "handleMessage_play ");

                        } else {
                            bottom_pause.setBackgroundResource(R.drawable.bt_pause_music);

                        }


                    } catch (RemoteException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    break;

                case MSG_UPPALY_BTN:
                    try {

                        if (mService.getMusicIsPlaying()) {
                            bottom_pause.setBackgroundResource(R.drawable.bt_play_music);
                            updateUi();
                        } else {
                            bottom_pause.setBackgroundResource(R.drawable.bt_pause_music);

                        }
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
            }
            super.handleMessage(msg);
        }
    };

    //接收到发过来的广播,更新 ui
    public class UpdateUiBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            mHandler.sendEmptyMessage(MSG_UPDATE_UI);
        }
    }

//    /**
//     * 定义闹钟广播接收者
//     **/
//    private BroadcastReceiver mAlarmReceiver = new BroadcastReceiver() {
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            Log.i("lanou99999999999", "close");
//            stopService(new Intent(MainActivity.this, MusicService.class));
//            android.os.Process.killProcess(android.os.Process.myPid());
//            System.exit(0);
//        }
//    };

    /**
     * 从播放列表中传来的值
     */

    @Override
    public void onItemWhere(int position) {

        try {
            if (mService.getMusicIsPlaying()) {
                mService.stopMusic();
            }
            mService.setNowPlay(position);
            mService.setDataSourceAndPlay();


            if (mList != null && mList.size() > 0) {
                updateUi();
            }

            bottom_pause.setBackgroundResource(R.drawable.bt_play_music);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }


}



